package proj3;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Visualizer {
	private int _area_width;
	private int _area_height;
	private int[] _trackerX;
	private int _player_width;
	private int[] _boxX;
	private int[] _boxY;
	private int[] _boxWidth;
	private int _scale = 20;
	private int _index;
	
	Visualizer(int area_width, int area_height, int[] trackerX, int player_width, int[] boxX, int[] boxY, int[] boxWidth) {
		_area_width = area_width;
		_area_height = area_height;
		_trackerX = trackerX;
		_player_width = player_width;
		_boxX = boxX;
		_boxY = boxY;
		_boxWidth = boxWidth;
		_index = 0;
	}
	
	
	
	public void visualize() {
		JFrame frame = new javax.swing.JFrame("Hello world");
		Insets insets = frame.getInsets();
		frame.setSize(_area_width * _scale + insets.left + insets.right, _area_height * _scale + insets.bottom + insets.top);
		
		final JPanel drawingArea = new JPanel() {
			@Override
			protected void paintComponent(Graphics g) {
				super.paintComponent(g);
				if(_index >= _boxX.length)return;
				
				Graphics2D g2d = (Graphics2D) g;
				
				//draw box
				g2d.setColor(Color.RED);
				int boxX = _boxX[_index] % _area_width;
				int boxY = _boxY[_index];
				int boxWidth = _boxWidth[_index];
				int playerX = _trackerX[_index] % _area_width;
				while (boxX < 0)boxX += _area_width;
				while (playerX < 0)playerX += _area_width;
				//before-wrap
				int box_end = Math.min(boxX + boxWidth, _area_width);
				g2d.fillRect(boxX*_scale, (_area_height - boxY)*_scale, (box_end - boxX)*_scale, _scale);
				if ((boxX + boxWidth) - box_end > 0)
					g2d.fillRect(0, (_area_height - boxY)*_scale, (boxX + boxWidth - box_end)*_scale, _scale);
				
				//draw player
				g2d.setColor(Color.BLUE);
				int player_end = Math.min(playerX + _player_width, _area_width);
				g2d.fillRect(playerX*_scale, (_area_height - 1)*_scale, (player_end - playerX)*_scale, _scale);
				if (playerX + _player_width - player_end > 0)
					g2d.fillRect(0,  (_area_height - 1)*_scale,  (playerX + _player_width - player_end)*_scale, _scale);
			}
		};
		
		drawingArea.setPreferredSize(new Dimension(_area_width*_scale, _area_height*_scale));
		drawingArea.setBackground(Color.WHITE);
		
		frame.getContentPane().add(drawingArea);
		frame.pack();
		frame.setVisible(true);
		
		ActionListener tick = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				drawingArea.repaint();
				if (_index >= _trackerX.length) {
					((Timer) e.getSource()).stop();
					System.exit(0);
				}
				_index++;
			}
		};
		new Timer(100, tick).start();
	}

}
